//
//  RouteDetaliController.m
//  Cycling
//
//  Created by 迟国强 on 2023/4/5.
//

#import "RouteDetaliController.h"
#import "RouteDetailMessageCell.h"
#import "CommentTableViewCell.h"
#import "HeightTableCell.h"
#import "RouteRequest.h"
#import "RouteDetailModel.h"
#import <CoreLocation/CoreLocation.h>

#import "Cycling-Swift.h"
#import "AppDelegate.h"
#import "CommentView.h"
#import "CommentListViewController.h"
#import "ImageCollectionViewCell.h"
@interface RouteDetaliController ()<UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) NSMutableArray *dataArray;  // 列表数据
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) RouteDetailModel *detailModel;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, strong) UIButton *toStartBtn;
@property (nonatomic, strong) UIButton *startCyclingBtn;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation RouteDetaliController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"路线详情";
    self.view.backgroundColor = rgbHex(0xF8F8F8, 1);
    
    self.dataArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NavigationBarHeight);
        make.bottom.equalTo(self.view).offset(-SafeAreaBottomHeight);
        make.left.right.equalTo(self.view).offset(0);
    }];
    [self setHeaderFooterView];
    [self startLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"CommentSubNotification" object:nil];
    
}

- (void)setHeaderFooterView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 202) collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.clearColor;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.pagingEnabled = YES;
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (@available(iOS 11.0, *)) {
        collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [collectionView registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ImageCollectionViewCell"];

    self.collectionView = collectionView;
    self.tableView.tableHeaderView = collectionView;
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 94)];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(20, 10, (SCREEN_W - 50)/2, 54);
    saveBtn.backgroundColor = rgb(30, 214, 194);
    [saveBtn setTitle:@"导航到起点" forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 27;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(navigateToTheStartingPoint) forControlEvents:(UIControlEventTouchUpInside)];
    [footer addSubview:saveBtn];
    self.toStartBtn = saveBtn;
    
    UIButton *cyclingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cyclingBtn.frame = CGRectMake(30 + (SCREEN_W - 50)/2, 10, (SCREEN_W - 50)/2, 54);
    cyclingBtn.backgroundColor = rgba(30, 214, 194, 0.1);
    [cyclingBtn setTitle:@"开始骑行" forState:UIControlStateNormal];
    [cyclingBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    cyclingBtn.layer.cornerRadius = 27;
    cyclingBtn.layer.masksToBounds = YES;
    [footer addSubview:cyclingBtn];
    self.startCyclingBtn = cyclingBtn;
    [cyclingBtn addTarget:self action:@selector(startToRide) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.tableView.tableFooterView = footer;

}

- (void)loadData {
    [RouteRequest getRouteDetailWithId:self.model.id lat:[NSString stringWithFormat:@"%f",self.myLocation.coordinate.latitude] lng:[NSString stringWithFormat:@"%f",self.myLocation.coordinate.longitude] result:^(RouteDetailModel * _Nonnull detail) {
        if (detail != nil) {
            NSMutableArray *arr = [NSMutableArray array];
            for (int i = 0; i < detail.comments.count; i++) {
                RouteCommentModel *model = detail.comments[i];
                model.isSuper = YES;//是否是第一层
                [arr addObject:model];
                if (model.rec.count != 0) {
                    [arr addObjectsFromArray:model.rec];
                }
            }
            self.detailModel = detail;
            self.detailModel.comments = arr;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateUI];
            });
        }
    }];
}

- (void)updateUI {
    if (self.detailModel.isOrigin) {
        self.toStartBtn.backgroundColor = rgb(30, 214, 194);
        self.startCyclingBtn.backgroundColor = rgba(30, 214, 194, 0.1);
    } else {
        self.toStartBtn.backgroundColor = rgb(30, 214, 194);
        self.startCyclingBtn.backgroundColor = rgba(30, 214, 194, 0.1);
    }
    if(self.detailModel.imgs.count){
        self.dataArr = [NSMutableArray arrayWithArray:self.detailModel.imgs];
    }else {
        if(self.detailModel.lineimg.length){
            self.dataArr = [NSMutableArray arrayWithArray:@[self.detailModel.lineimg]];
        }
    }
    [self.collectionView reloadData];
    [self.tableView reloadData];
    [self removeLoadingView];
    
}

#pragma mark - tableView delegate datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.detailModel == nil) {
        return 0;
    }
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        RouteDetailMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RouteDetailMessageCell"];
        cell.model = self.detailModel;
        cell.collectionBlock = ^(RouteDetailModel * _Nonnull model) {
            if (model.iscollection) {
                [RouteRequest cancleCollectionRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                    model.iscollection = NO;
                    model.collectionnum = [NSString stringWithFormat:@"%d", model.collectionnum.intValue - 1];

                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                }];
            } else {
                [RouteRequest collectionRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                    model.iscollection = YES;
                    model.collectionnum = [NSString stringWithFormat:@"%d", model.collectionnum.intValue + 1];
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                }];
            }
        };
        cell.goodBlock = ^(RouteDetailModel * _Nonnull model) {
            if (model.ispraise) {
                [RouteRequest cancelPraiseRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                    model.ispraise = NO;
                    model.praisenum = [NSString stringWithFormat:@"%d", model.praisenum.intValue - 1];
                    [self.tableView reloadData];
                }];
            } else {
                [RouteRequest praiseRouteWithRouteId:model.id result:^(NSDictionary * _Nonnull ret) {
                    model.ispraise = YES;
                    model.praisenum = [NSString stringWithFormat:@"%d", model.praisenum.intValue + 1];
                    [self.tableView reloadData];
                }];
            }
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.row == 1) {
        HeightTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HeightTableCell"];
        cell.hight = self.detailModel.highly;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.hidden = self.detailModel.highly.data.count == 0;
        return cell;
    }
    else {
        CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentTableViewCell"];
        cell.models = self.detailModel.comments;
        cell.detailModel = self.detailModel;
        cell.block = ^(RouteDetailModel * _Nonnull model) {
            [CommentView CommentWith:self Complection:^(NSString * _Nonnull content) {
                [self commentRouteWith:content];
                [NSObject.getKeyWindowRootViewController gq_removeBgView];
            }];
        };
        cell.listBlock = ^(RouteCommentModel * _Nonnull model) {
            CommentListViewController *vc = [[CommentListViewController alloc] init];
            vc.pid = self.detailModel.id;
            vc.commentPid = model.id;
            vc.isSuper = NO;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.moreBlock = ^(RouteDetailModel * _Nonnull model) {
            CommentListViewController *vc = [[CommentListViewController alloc] init];
            vc.pid = self.detailModel.id;
            vc.isSuper = YES;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)commentRouteWith:(NSString *)text {
    [RouteRequest commentsRouteWithRouteId:self.detailModel.id text:text recid:@"" result:^(BOOL success) {
        if (success) {
            [self showHudTipStr:@"评论成功"];
            [self loadData];
        }
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 206;
    } else if (indexPath.row == 1) {
        if (self.detailModel.highly.data.count == 0) {
            return CGFLOAT_MIN;
        } else {
            return 225;
        }
    } else {
        CGFloat h = 66;
        for (int i = 0; i < self.detailModel.comments.count; i++) {
            RouteCommentModel *model = self.detailModel.comments[i];
            CGSize size = [model.content boundingRectWithSize:CGSizeMake(SCREEN_W-60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:PingFangFont(20)} context:nil].size;
            h += 90 + size.height;
        }
        if ([self.detailModel.commnum intValue] <= 3 && [self.detailModel.commnum intValue] > 0) {
            return h;
        }
        else {
            return 60 + h;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = rgbHex(0xF8F8F8, 1);
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }
        if (@available(iOS 11.0, *) ) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"HeightTableCell" bundle:nil] forCellReuseIdentifier:@"HeightTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"CommentTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"RouteDetailMessageCell" bundle:nil] forCellReuseIdentifier:@"RouteDetailMessageCell"];
    }
    return _tableView;
}

// 导航到起点
- (void)navigateToTheStartingPoint {
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.detailModel reloadJsonModels];
    [AppDelegate changeToCyclingTabWithRouteJson:self.detailModel.json andLat:self.detailModel.startlat.doubleValue lng:self.detailModel.startlng.doubleValue];
}

// 开始骑行
- (void)startToRide {
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.detailModel reloadJsonModels];
    [AppDelegate changeToCyclingTabWithRouteJson:self.detailModel.json];
}

//开始定位
- (void)startLocation {
    //初始化定位管理者
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    //判断设备是否能够进行定位
    if ([CLLocationManager locationServicesEnabled]) {
        //精确度获取到米
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置过滤器为无
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        // 取得定位权限，有两个方法，取决于你的定位使用情况
        //一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
        [self.locationManager requestWhenInUseAuthorization];
        //开始获取定位
        [self.locationManager startUpdatingLocation];
        //地理信息
//        self.geoCoder = [[CLGeocoder alloc] init];
    } else {
        DebugLog(@"error");
    }
}

//设置获取位置信息的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%lu", (unsigned long)locations.count);
    self.myLocation = locations.lastObject;
    DebugLog(@"经度：%f 纬度：%f", _myLocation.coordinate.longitude, _myLocation.coordinate.latitude);
    
    //不用的时候关闭更新位置服务，不关闭的话这个 delegate 隔一定的时间间隔就会有回调
    [self.locationManager stopUpdatingLocation];
    [self loadData];
    
}
//问题函数
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error) {
        [self loadData];

        DebugLog(@"error:%ld", (long)error.code);
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

#pragma collectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ImageCollectionViewCell" owner:self options:nil] lastObject];
    }
    cell.imurl = self.dataArr[indexPath.row];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_W, 205);
}

@end
